package net.xo68.destiny.starter.manager.security;

import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.common.SystemConstants;
import net.xo68.destiny.contract.domain.StringRespondResult;
import net.xo68.destiny.core.json.JsonMapper;
import net.xo68.destiny.starter.common.SchedulerCommonProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 工作节点接口调用认证过滤器
 * @author wuxie
 * @version 2020-11-3
 */
@Slf4j
public class ApiAuthorizationFilter extends OncePerRequestFilter {

    private final SchedulerCommonProperties schedulerCommonProperties;
    private final JsonMapper jsonMapper;
    private final String antPattern;
    private final AntPathRequestMatcher requestMatcher;

    public ApiAuthorizationFilter(SchedulerCommonProperties schedulerCommonProperties,JsonMapper jsonMapper,String antPattern) {
        this.schedulerCommonProperties = schedulerCommonProperties;
        this.jsonMapper=jsonMapper;
        this.antPattern=antPattern;
        this.requestMatcher=new AntPathRequestMatcher(this.antPattern);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //非api路径跳过验证
        if(!requestMatcher.matches(request)){
            filterChain.doFilter(request, response);
            return;
        }
        String authToken = request.getHeader(SystemConstants.API_TOKEN_HEADER);
        if (StringUtils.isNotEmpty(authToken) && authToken.startsWith(SystemConstants.API_TOKEN_PREFIX)) {
            authToken = authToken.substring(SystemConstants.API_TOKEN_PREFIX.length());
        } else {
            // 不按规范,不允许通过验证
            authToken = null;
        }

        //log.debug("request uri:{}", request.getRequestURI());
        if (StringUtils.isNotEmpty(authToken) && authToken.equals(schedulerCommonProperties.getApiAccessToken())) {
            filterChain.doFilter(request, response);
        }else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(jsonMapper.toString(StringRespondResult.fail("Access Denied"),true));
            response.getWriter().flush();
        }

    }
}
